import request from "utils/request";

const remoteRoute = [
  {
    path: "/user",
    name: "User",
    component: "options/pages/home/pages/user/user",
    title: "用户管理",
    sort:0
  },
  {
    path: "/role",
    name: "Role",
    component: "options/pages/home/pages/role/role",
    title: "角色管理",
    sort:0
  },
  {
    path: "/authority",
    name: "Authority",
    component: "options/pages/home/pages/authority/authority",
    title: "菜单管理",
    sort:0
  },
  {
    path: "/video",
    name: "Video",
    component: "options/pages/home/pages/video/video",
    title: "视频管理",
    sort:0
  },
];
const _import = (component) => () => import(`src/${component}.vue`);

/**
 * 排序
 * @param {*} a 
 * @param {*} b 
 * @returns 
 */
const up = function (a, b) {
  return a.meta.sort - b.meta.sort;
};

const filterRoutes = (routes) => {
  return routes
    .map((route) => {
      return {
        path: route.path,
        name: route.name,
        component: _import(route.component),
        meta: {
          title: route.title,
          sort: route.sort,
        },
      };
    })
    .sort(up);
};

const state = {
  accessRoutes: [],
  isGetAccessRoute:false
};

const mutations = {
  updateMenu(state, accessRoutes) {
    state.accessRoutes = accessRoutes;
  },
  updateGetAccessRoute(state, isGetAccessRoute) {
    state.isGetAccessRoute = isGetAccessRoute;
  },
  clearAccessRoute(){
    state.isGetAccessRoute = false;
    state.accessRoutes=[]
  }
};
const actions = {
  getMenus({ commit }) {
    return new Promise((resolve, reject) => {
      request.get("getSelfPermissionList").then((ret) => {
        if (ret.code == 200) {
          const accessRoutes = filterRoutes(ret.data);
          commit("updateMenu", accessRoutes);
          commit("updateGetAccessRoute", true);
          resolve(accessRoutes);
        } else {
          reject(ret.message);
        }
      });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
